package com.jiesen.base.modules.login.jsRole.controller;

import com.alibaba.fastjson.JSONObject;
import com.jiesen.base.modules.login.jsRole.model.JsRole;
import com.jiesen.base.modules.login.jsRole.service.JsRoleService;
import com.jiesen.base.utils.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/login/role")
public class RoleController {

    @Autowired
    public JsRoleService jsRoleService;

    //根据角色id查询角色信息
    @GetMapping("/view")
    //@RequiresPermissions("jsuser")
    public R viewUser(@RequestParam("id")String id){
        JsRole jsRole = jsRoleService.getById(id);
        if(jsRole==null){
            return R.error("没有角色");
        }
        return R.ok().put("data",jsRole);
    }

    @PostMapping("/view")
    //@RequiresPermissions("jsuser")
    public R viewUser(@RequestBody JsRole jsRole){
        return jsRoleService.page(jsRole);
    }

    //增加一个后台登录角色
    @PostMapping("/create")
    public R creacrUser(@RequestBody JsRole jsRole){
        jsRole.setAddtime(new Date());
        boolean save = jsRoleService.save(jsRole);
        if(!save){
            return R.error("添加失败");
        }
        return R.ok();
    }

    //删除一个后台登录角色
    @GetMapping("/delete")
    public R deleteUser(@RequestParam("id")String id){
        boolean save = jsRoleService.removeById(id);
        if(!save){
            return R.error("删除失败");
        }
        return R.ok();
    }

    //修改一个后台角色
    @PostMapping("/edit")
    public R deitUser(@RequestBody JsRole jsRole){
        jsRole.setUpdatetime(new Date());
        boolean save = jsRoleService.updateById(jsRole);
        if(!save){
            return R.error("修改失败");
        }
        return R.ok();
    }

    //根据角色id查询角色拥有的权限
    @GetMapping("/permission/view")
    public R viewRolePermission(@RequestParam("id")String id){
        JsRole role = jsRoleService.getByIdAndPermission(id);
        if (role == null){
            return R.error("没有该角色");
        }
        return R.ok().put("data",role);
    }

    //给角色修改权限
    @PostMapping("/permission/add")
    public R addPermission(@RequestBody JsRole jsRole) {
        List<Integer> pid = jsRole.getPids();
        boolean i = jsRoleService.updataRolePermission(jsRole.getId(), pid);
        if (!i) {
            return R.error();
        }
        return R.ok();
    }

}
